﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Collections.Specialized;
using MVCPets.Helpers;
using System.Web.Security;

namespace MVCPets.Extensions.Web
{
  public static class SessionExtensions
  {
    /// <summary>
    /// Attempts to pull a strongly typed value from the Session.
    /// If it is not found or the conversion fails then it returns the
    /// last parameter.
    /// </summary>
    /// <typeparam name="T">The type of the item</typeparam>
    /// <param name="data">The Session object object</param>
    /// <param name="param">The key</param>
    /// <param name="defaultValue">The default value to return</param>
    /// <returns>The converted type or the default value</returns>
    public static T GetItem<T>(this HttpSessionState data, string param, T defaultValue)
    {
      if(data.IsNewSession && data.Keys.Count == 0)
      {
        FormsAuthentication.SignOut();
        //HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl);
        //HttpContext.Current.Response.End();
      }

      if(data != null && data[param] != null)
        return ConversionHelpers.ConvertItem<T>(data[param] as object, defaultValue);
      else
        return defaultValue;
    }    
  }
}